<?php

namespace App\Kuafu\Mqtt\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Log extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysqlMQTT';
    protected $table      = 'mqtt_log';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'id',
        'shopId',
        'cmd',
        'params',
        'status',
        'createdAt',
        'updatedAt'
    ];

    const STATUS_INIT      = 0;  // 状态：初始
    const STATUS_ACKED     = 1;  // 状态：已发送
    const STATUS_DELIVERED = 2;  // 状态：已送达
    const STATUS_FINISHED  = 3;  // 状态：完成
    const STATUS_ERROR     = 4;  // 状态：错误

    /**
     * 添加日志
     * @param $shopId
     * @param $data
     * @return Builder|Model
     */
    public static function add($shopId, $data, $status = self::STATUS_INIT)
    {
        return self::query()->create([
            'id'        => $data['id'],
            'shopId'    => $shopId,
            'cmd'       => $data['cmd'],
            'params'    => is_array($data['params']) ? json_encode($data['params']) : "",
            'status'    => $status,
            'createdAt' => time(),
            'updatedAt' => 0
        ]);
    }

    /**
     * 更新日志状态
     *
     * @param $id
     * @param int $status
     * @return int
     */
    public static function setStatus($ids, int $status = self::STATUS_FINISHED): int
    {
        return self::query()->whereIn('id', $ids)->update([
            'status'    => $status,
            'updatedAt' => time()
        ]);
    }

    public static function getList($condition, $field)
    {
        return self::query()
                   ->where($condition)
                   ->select($field)
                   ->orderBy('id', 'DESC')
                   ->first();
    }
}
